#!/bin/bash

exec_path=$(readlink -f "$0");
export script_base_folder=$(dirname "$exec_path");

export local_folder="";
export folder_name="";

while [[ $# -ge 1 ]]; do
    case $1 in
        -f|--folder)
            shift;
            folder_name="$1";
            shift;
            ;;
        *)
            local_folder="$1";
            break;
            ;;
    esac
done

local_folder="$(echo "$local_folder" |sed 's/^[[:space:]]*\|[[:space:]]*$//g')";
folder_name="$(echo "$folder_name" |sed 's/^[[:space:]]*\|[[:space:]]*$//g' |sed 's/^\///' |sed 's/\/$//')";

function error_msg() {
    echo "$1";
    exit 1;
}

function get_local_folder() {
    IFS=$'\n'
    for local_name in `ls -A1 .`
      do
        if [[ -d "${local_name}" ]]; then
          eval cd \'$local_name\'
          get_local_folder;
          cd ..
        else
          if [[ -n "$folder_name" ]]; then
            local_folder_name="${folder_name}/$(readlink -f ./ |sed 's|'$local_folder_base'||' |sed 's|^/||')";
          else
            local_folder_name="$(readlink -f ./ |sed 's|'$local_folder_base'||' |sed 's|^/||')";
          fi
          eval "${script_base_folder}/onedrive" -f \'$local_folder_name\' \'$local_name\';
        fi
      done
    }

if [ ! -e "${script_base_folder}/onedrive" ]; then
  error_msg "Error! Not found 'onedrive'.";
fi

if [[ -z "${local_folder}" ]]; then
  error_msg "No file to upload.";
fi

if [[ -d "${local_folder}" ]]; then
  dir -d "${local_folder}" >/dev/null 2>&1;
  if [[ $? -ne '0' ]]; then
    error_msg "Error! Not access to the folder.";
  fi
  cd "${local_folder}";
  local_folder_base="$(dirname "$(readlink -f ./)")";
  get_local_folder;
elif [[ -f "${local_folder}" ]]; then
  eval "${script_base_folder}/onedrive" \'$local_folder\';
else
  error_msg "Invalid item.";
fi
